package controleur;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JMenuItem;

import vue.WindowEditor;
import modele.Plugin;
import modele.PluginAddedEvent;
import modele.PluginEventlistener;
/**
 * add automatically the plugins per seconds 
 * @author morhib & moyart
 *
 */
public class PluginEventControl implements PluginEventlistener {

	WindowEditor f;

	public PluginEventControl(WindowEditor w) {
		this.f=w;
	}

	@Override
	public void pluginAdded(PluginAddedEvent p) {

		/* add jMenuItem in jMenu bar */
		File file = p.getFile();
		String classname = file.getName().replaceFirst("\\.class$", "");
		System.out.println(classname);
		try {
			final Plugin pluuu = (Plugin) Class.forName(
					"plugins." + classname).newInstance();
			JMenuItem jmiPluggin = new JMenuItem(classname);
			jmiPluggin.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					f.getTextArea().setText(pluuu.transformString(f.getTextArea().getText()));
				}
			});
			f.getTools().add(jmiPluggin);
		} catch (InstantiationException e) {
			// the class is abstract where the  interface has no accessible 
			// constructor 
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// the class is not accessible
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			//the class doesn't exist
			e.printStackTrace();
		}
	}

}